package geektime.jdk.secret;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.nio.charset.StandardCharsets;
import java.security.*;

/**
 * 简单演示非对称加解密
 */
public class CryptoDemo {
    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        String content = "Good morning";
        // 基于RSA算法创建一个非对称秘钥生成器
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        // 随机生成一组公钥和私钥
        KeyPair keyPair = generator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();
        // 基于RSA算法创建一个加密器，使用公钥进行初始化
        Cipher cipher1 = Cipher.getInstance("RSA");
        cipher1.init(Cipher.PUBLIC_KEY, publicKey);
        // 对明文内容content进行非对称加密
        byte[] encryptResult = cipher1.doFinal(content.getBytes(StandardCharsets.UTF_8));

        // 基于RSA算法创建一个解密器，使用私钥进行初始化
        Cipher cipher2 = Cipher.getInstance("RSA");
        cipher2.init(Cipher.PRIVATE_KEY, privateKey);
        // 对加密内容进行非对称解密
        cipher2.update(encryptResult);
        byte[] decryptResult = cipher2.doFinal();
        System.out.println("decryptResult: " + new String(decryptResult, StandardCharsets.UTF_8));
    }
}
